package com.wx.house.manager.api.permission.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.wx.house.manager.api.permission.service.SysMenusService;
import com.wx.house.manager.api.permission.text.SysRoleMenuPame;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.wx.house.manager.api.permission.service.SysRoleMenuService;
import com.wx.house.common.base.BaseController;
import com.wx.house.common.exception.BusinessException;
import com.wx.house.common.util.IDUtils;
import com.wx.house.core.pojo.base.Result;
import com.wx.house.core.pojo.po.SysRoleMenu;
import com.wx.house.core.pojo.vo.SysMenusVo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("SysRoleMenu/")
@Api(value = "角色菜单模块", tags = "模块:角色菜单模块")
@Slf4j
public class SysRoleMenuController extends BaseController{
	@Resource
	private SysRoleMenuService sysRoleMenuService;
	@Resource
	private SysMenusService sysMenusService;
	
	@ApiOperation(value = "菜单分配", notes = "菜单分配")
	@PostMapping("SysRoleMenu/")
	public Result addRoleMenu(@RequestBody @Validated SysRoleMenuPame sysRoleMenuPame, HttpServletRequest request) {
		try {
			//step 1.删除角色菜单
			sysRoleMenuService.dateRoleMenu(sysRoleMenuPame.getRoleId());
			//step 2.循环添加
			for (int i = 0; i < sysRoleMenuPame.getMenuId().size(); i++) {
				List<String> lis = Arrays.asList(sysRoleMenuPame.getMenuId().get(i).getPermissionId().split(","));
				List<String> unique = lis.stream().distinct().collect(Collectors.toList());
				SysRoleMenu sysRoleMenu=SysRoleMenu
						.builder()
						.id(IDUtils.genItemId(8)+"")
						.roleId(sysRoleMenuPame.getRoleId())
						.menuId(sysRoleMenuPame.getMenuId().get(i).getMenuId())
						.permissionId(String.join(",", unique))
						.operation("李好")
						.operationTime(new Date())
						.build();
				sysRoleMenuService.addRoleMenu(sysRoleMenu);
			}
			return Result.success("分配菜单成功");
		} catch (Exception e) {
			throw new BusinessException("分配菜单失败");
		}
	}
	/***
	 * 查询菜单树
	 */
	@ApiOperation(value = "根据角色查询菜单", notes = "根据角色查询菜单")
	@GetMapping("SeleMenusTree/")
    public Result<List<SysMenusVo>> getTree(String roleId) {
    	List<SysMenusVo> Menus=sysMenusService.sysRoleMenuslist(roleId);
        List<SysMenusVo> baseLists = new ArrayList<>();
        // 总菜单，出一级菜单，一级菜单没有父id
        for (SysMenusVo e: Menus) {
            if( "0".equals(e.getPId())){
                baseLists.add( e );
            }
        }
        // 遍历一级菜单
        for (SysMenusVo e: baseLists) {
            // 将子元素 set进一级菜单里面
            e.setChild( getChild(e.getId(),Menus) );
        }
        return Result.success(baseLists);
    }
    /**
     * 获取子节点
     * @param pid
     * @param elements
     * @return
     */
    private List<SysMenusVo> getChild(String pid , List<SysMenusVo> elements){
        List<SysMenusVo> childs = new ArrayList<>();
        for (SysMenusVo e: elements) {
            if(!"0".equals(e.getPId())){
                if(e.getPId().equals( pid )){
                    // 子菜单的下级菜单
                    childs.add( e );
                }
            }
        }
        // 把子菜单的子菜单再循环一遍
        for (SysMenusVo e: childs) {
            // 继续添加子元素
            e.setChild( getChild( e.getId() , elements ) );
        }
        //停下来的条件，如果 没有子元素了，则停下来
        if( childs.size()==0 ){
            return null;
        }
        return childs;
    }
}